package module.course.impl;

import common.model.Entity.Student;
import common.model.Entity.User;
import common.model.Entity.courseEntity.CourseLocation;
import common.model.Entity.courseEntity.CourseSchedule;
import common.util.TransactionManager;
import dao.CourseDao.CourseScheduleDao;
import dao.CourseDao.CourseDao;
import common.model.Entity.courseEntity.Course;
import dao.CourseDao.CourseLocationDao;
import dao.StudentDao;
import dao.UserDao;
import dao.impl.CourseDaoImpl.CourseDaoImpl;
import dao.impl.CourseDaoImpl.CourseScheduleDaoImpl;
import dao.impl.StudentDaoImpl;
import dao.impl.CourseDaoImpl.CourseLocationDaoImpl;
import dao.impl.UserDaoImpl;
import module.course.CourseService;
import network.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
/**
 * 课程服务实现类，提供课程的增删改查、选课、退课、排课和教室管理等功能。
 * 实现 {@link CourseService} 接口。
 */
public class CourseServiceImpl implements CourseService {
    private static final Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);

    private final CourseDao courseDao;
    private final CourseScheduleDao courseScheduleDao;
    private final CourseLocationDao courseLocationDao;
    private final UserDao userDao;
    private final static CourseService INSTANCE = new CourseServiceImpl();

    /**
     * 获取 {@link CourseServiceImpl} 单例对象。
     *
     * @return CourseService 实例
     */
    public static CourseService getInstance(){
        return INSTANCE;
    }

    /**
     * 默认构造函数，初始化各 DAO 实例。
     */
    public CourseServiceImpl() {
        this.courseDao = new CourseDaoImpl();
        this.courseScheduleDao = new CourseScheduleDaoImpl();
        this.userDao = new UserDaoImpl();
        this.courseLocationDao = new CourseLocationDaoImpl();
    }
    /**
     * 根据课程 ID 查询课程。
     *
     * @param id 课程 ID
     * @return Response 封装的课程对象或错误信息
     */
    @Override
    public Response<Course> findById(Long id) {
        try {
            Course course = courseDao.findById(id)
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + id));
            return Response.success(course);
        } catch (Exception e) {
            logger.error("根据ID查询课程失败: id={}", id, e);
            return Response.error("查询课程失败: " + e.getMessage());
        }
    }
    /**
     * 查询所有课程。
     *
     * @return Response 封装的课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findAll() {
        try {
            List<Course> courses = courseDao.findAll();
            return Response.success(courses);
        } catch (Exception e) {
            logger.error("查询所有课程失败", e);
            return Response.error("查询所有课程失败: " + e.getMessage());
        }
    }
    /**
     * 根据课程名称查询课程列表。
     *
     * @param name 课程名称
     * @return Response 封装的课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findByName(String name) {
        try {
            List<Course> courses = courseDao.findByCourseName(name);
            return Response.success(courses);
        } catch (Exception e) {
            logger.error("根据名称查询课程失败: name={}", name, e);
            return Response.error("根据名称查询课程失败: " + e.getMessage());
        }
    }
    /**
     * 根据教师 ID 查询教师姓名。
     *
     * @param id 教师 ID
     * @return Response 封装的教师姓名或错误信息
     */
    @Override
    public Response<String> findTeacherNameByTeacherId(Long id){
        try {
            User user = userDao.findById(id).get();
            return Response.success(user.getRealName());
        } catch (Exception e) {
            logger.error("根据id查询老师失败{}",  e.getMessage());
            return Response.error("根据id查询老师失败: " + e.getMessage());
        }
    }
    /**
     * 根据课程 ID 查询课程排课信息。
     *
     * @param id 课程 ID
     * @return Response 封装的课程排课列表或错误信息
     */
    @Override
    public Response<List<CourseSchedule>> findCourseWithSchedule(Long id){
        try {
            List<CourseSchedule> schedules = courseScheduleDao.findByCourseId(id);
            return Response.success(schedules);
        } catch (Exception e) {
            logger.error("查询课程的时间失败{}{}", id,e.getMessage());
            return Response.error("根据id查询课程时间: " + e.getMessage());
        }
    }
    /**
     * 创建新课程。
     *
     * @param course 待创建课程对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> createCourse(Course course) {
        try {
            // 验证课程信息
            validateCourse(course);

            // 设置默认值
            if (course.getCurrentEnrollment() == null) {
                course.setCurrentEnrollment(0);
            }
            if (course.getStatus() == null) {
                course.setStatus(0); // 默认禁用
            }

            boolean success = courseDao.save(course);
            if (success) {
                return Response.success(true);
            } else {
                return Response.error("创建课程失败");
            }
        } catch (Exception e) {
            logger.error("创建课程失败: {}", course, e);
            return Response.error("创建课程失败: " + e.getMessage());
        }
    }
    /**
     * 更新课程信息。
     *
     * @param course 待更新课程对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> updateCourse(Course course) {
        try {
            // 验证课程是否存在
            Course existingCourse = courseDao.findById(course.getId())
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + course.getId()));

            // 验证课程信息
            validateCourse(course);

            boolean success = courseDao.update(course);
            if (success) {
                return Response.success(true);
            } else {
                return Response.error("更新课程失败");
            }
        } catch (Exception e) {
            logger.error("更新课程失败: {}", course, e);
            return Response.error("更新课程失败: " + e.getMessage());
        }
    }
    /**
     * 删除课程。
     *
     * @param id 课程 ID
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> deleteCourse(Long id) {
        try {
            // 验证课程是否存在
            Course existingCourse = courseDao.findById(id)
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + id));

            // 检查是否有学生选课
            if (existingCourse.getCurrentEnrollment() > 0) {
                return Response.error("课程还有学生选课，无法删除");
            }

            // 删除课程的排课信息
            boolean scheduleDeleted = courseScheduleDao.deleteByCourseId(id);
            if (!scheduleDeleted) {
                logger.warn("删除课程排课信息失败，但继续尝试删除课程");
            }

            boolean success = courseDao.deleteById(id);
            if (success) {
                return Response.success(true);
            } else {
                return Response.error("删除课程失败");
            }
        } catch (Exception e) {
            logger.error("删除课程失败: id={}", id, e);
            return Response.error("删除课程失败: " + e.getMessage());
        }
    }
    /**
     * 学生选课。
     *
     * @param courseId 课程 ID
     * @param studentId 学生 ID
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> enrollStudent(Long courseId, Long studentId) {
        try {
            // 开始事务
            TransactionManager.beginTransaction();

            // 验证课程是否存在
            Course course = courseDao.findById(courseId)
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + courseId));

            // 验证学生是否存在
            User student = userDao.findById(studentId)
                    .orElseThrow(() -> new RuntimeException("学生不存在，ID: " + studentId));

            // 检查课程容量
            if (course.getCurrentEnrollment() >= course.getMaxCapacity()) {
                TransactionManager.rollback();
                return Response.error("课程已满，无法选课");
            }

            // 检查学生是否已经选过该课程
            if (courseDao.isStudentEnrolled(courseId, studentId)) {
                TransactionManager.rollback();
                return Response.error("学生已经选过该课程");
            }

            // 插入选课记录
            boolean enrollmentRecordSuccess = courseDao.enrollStudentInCourseTable(courseId, studentId);
            if (!enrollmentRecordSuccess) {
                TransactionManager.rollback();
                logger.error("插入选课记录失败: courseId={}, studentId={}", courseId, studentId);
                return Response.error("选课操作失败");
            }

            // 增加选课人数
            boolean enrollmentSuccess = courseDao.incrementEnrollment(courseId);
            if (!enrollmentSuccess) {
                TransactionManager.rollback();
                logger.error("增加选课人数失败: courseId={}, studentId={}", courseId, studentId);
                return Response.error("选课操作失败");
            }

            // 提交事务
            TransactionManager.commit();
            logger.info("学生选课成功: courseId={}, studentId={}", courseId, studentId);
            return Response.success(true);
        } catch (Exception e) {
            // 回滚事务
            TransactionManager.rollback();
            logger.error("学生选课失败: courseId={}, studentId={}", courseId, studentId, e);
            return Response.error("选课失败: " + e.getMessage());
        } finally {
            // 结束事务
            TransactionManager.endTransaction();
        }
    }
    /**
     * 学生退课。
     *
     * @param courseId 课程 ID
     * @param studentId 学生 ID
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> dropStudent(Long courseId, Long studentId) {
        try {
            // 开始事务
            TransactionManager.beginTransaction();

            // 验证课程是否存在
            Course course = courseDao.findById(courseId)
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + courseId));

            // 验证学生是否选了该课程
            if (!courseDao.isStudentEnrolled(courseId, studentId)) {
                TransactionManager.rollback();
                return Response.error("学生未选该课程");
            }

            // 删除选课记录
            boolean enrollmentRecordSuccess = courseDao.dropStudentFromCourseTable(courseId, studentId);
            if (!enrollmentRecordSuccess) {
                TransactionManager.rollback();
                logger.error("删除选课记录失败: courseId={}, studentId={}", courseId, studentId);
                return Response.error("退课操作失败");
            }

            // 减少选课人数
            boolean enrollmentSuccess = courseDao.decrementEnrollment(courseId);
            if (!enrollmentSuccess) {
                TransactionManager.rollback();
                logger.error("减少选课人数失败: courseId={}, studentId={}", courseId, studentId);
                return Response.error("退课操作失败");
            }

            // 提交事务
            TransactionManager.commit();
            logger.info("学生退课成功: courseId={}, studentId={}", courseId, studentId);
            return Response.success(true);
        } catch (Exception e) {
            // 回滚事务
            TransactionManager.rollback();
            logger.error("学生退课失败: courseId={}, studentId={}", courseId, studentId, e);
            return Response.error("退课失败: " + e.getMessage());
        } finally {
            // 结束事务
            TransactionManager.endTransaction();
        }
    }
    /**
     * 根据课程 ID 查询选课学生列表。
     *
     * @param courseId 课程 ID
     * @return Response 封装学生列表或错误信息
     */
    @Override
    public Response<List<Student>> findStudentsByCourseId(Long courseId) {
        try {
            // 验证课程是否存在
            courseDao.findById(courseId)
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + courseId));

            List<Student> students = courseDao.findStudentsByCourseId(courseId);
            return Response.success(students);
        } catch (Exception e) {
            logger.error("查询课程学生失败: courseId={}", courseId, e);
            return Response.error("查询课程学生失败: " + e.getMessage());
        }
    }
    /**
     * 根据课程代码查询课程列表。
     *
     * @param code 课程代码
     * @return Response 封装课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findByCode(String code){
        try {
            List<Course> course = courseDao.findByCourseCode(code);
            return Response.success(course);
        } catch (Exception e) {
            logger.error("根据code查询课程失败: code={}", code, e);
            return Response.error("查询课程失败: " + e.getMessage());
        }
    }
    /**
     * 查询所有可选课程（状态为 true）。
     *
     * @return Response 封装课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findStatusTrue(){
        try {
            List<Course> course = courseDao.findStatusTrue();
            return Response.success(course);
        } catch (Exception e) {
            logger.error("查询全部可选课程失败{}", e.getMessage());
            return Response.error("查询课程失败: " + e.getMessage());
        }
    }
    /**
     * 教师申请课程。
     *
     * @param course 待申请课程对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> applyCourse(Course course) {
        try {
            // 教师申请课程，设置待审核状态
            course.setStatus(0); // 0表示待审核
            return createCourse(course);
        } catch (Exception e) {
            logger.error("教师申请课程失败: {}", course, e);
            return Response.error("申请课程失败: " + e.getMessage());
        }
    }
    /**
     * 教师更新自己开设的课程。
     *
     * @param teacherId 教师 ID
     * @param course 待更新课程对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> updateMyCourse(Long teacherId, Course course) {
        try {
            // 教师只能更新自己开设的课程
            Course existingCourse = courseDao.findById(course.getId())
                    .orElseThrow(() -> new RuntimeException("课程不存在，ID: " + course.getId()));

            // 检查当前用户是否是课程教师
            if (!existingCourse.getTeacherId().equals(teacherId)) {
                return Response.error("无权更新该课程");
            }

            // 验证课程信息
            validateCourse(course);

            boolean success = courseDao.update(course);
            if (success) {
                return Response.success(true);
            } else {
                return Response.error("更新课程失败");
            }
        } catch (Exception e) {
            logger.error("教师更新课程失败: teacherId={}, courseId={}", teacherId, course.getId(), e);
            return Response.error("更新课程失败: " + e.getMessage());
        }
    }
    /**
     * 根据教师姓名查询教师开设课程。
     *
     * @param teacherName 教师姓名
     * @return Response 封装课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findCoursesByTeacher(String teacherName) {
        try {
            List<Course> courses = courseDao.findByTeacherName(teacherName);
            return Response.success(courses);
        } catch (Exception e) {
            logger.error("查询教师课程失败: teacherName={}", teacherName, e);
            return Response.error("查询教师课程失败: " + e.getMessage());
        }
    }
    /**
     * 管理员排课操作。
     *
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> scheduleCourse() {
        try {
            logger.info("管理员排课功能调用");

            ScheduleCourseImpl scheduleCourse = new ScheduleCourseImpl();
            return scheduleCourse.scheduleCourse();
        } catch (Exception e) {
            logger.error("管理员排课失败", e);
            return Response.error("排课失败: " + e.getMessage());
        }
    }
    /**
     * 新增教室位置。
     *
     * @param location 教室对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> insertNewLocation(CourseLocation location){
        try{
            logger.info("插入新的教室");
            Boolean ret = courseLocationDao.save(location);
            return Response.success(ret);
        } catch (Exception e){
            logger.error("插入新教室失败：{}" , e.getMessage());
            return Response.error("插入失败" + e.getMessage());
        }
    }
    /**
     * 根据教室 ID 查询教室位置。
     *
     * @param id 教室 ID
     * @return Response 封装教室对象或错误信息
     */
    @Override
    public Response<CourseLocation> findLocationById(Long id){
        try {
            logger.info("根据ID查询教室位置: id={}", id);
            Optional<CourseLocation> location = courseLocationDao.findById(id);
            return location.map(Response::success).orElseGet(() -> Response.error("教室位置不存在，ID: " + id));
        } catch (Exception e) {
            logger.error("根据ID查询教室位置失败: id={}, {}", id, e.getMessage());
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 查询所有教室位置。
     *
     * @return Response 封装教室列表或错误信息
     */
    @Override
    public Response<List<CourseLocation>> findAllLocation(){
        try {
            logger.info("查询所有教室位置");
            List<CourseLocation> locations = courseLocationDao.findAll();
            return Response.success(locations);
        } catch (Exception e) {
            logger.error("查询所有教室位置失败: {}", e.getMessage());
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 更新教室信息。
     *
     * @param originLocation 原始教室对象
     * @param newLocation 新教室对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> updateLocation(CourseLocation originLocation, CourseLocation newLocation) {
        try {
            logger.info("更新教室位置: {}-{} -> {}-{}",
                    originLocation.getBuilding(), originLocation.getRoomNumber(),
                    newLocation.getBuilding(), newLocation.getRoomNumber());

            // 1. 根据原始信息查找教室位置
            Optional<CourseLocation> existingLocation = courseLocationDao.findByBuildingAndRoomNumber(
                    originLocation.getBuilding(), originLocation.getRoomNumber());

            if (existingLocation.isEmpty()) {
                return Response.error("原始教室位置不存在: " +
                        originLocation.getBuilding() + "-" + originLocation.getRoomNumber());
            }

            CourseLocation locationToUpdate = existingLocation.get();

            // 2. 检查新的教室位置是否与其他记录冲突（排除自己）
            Optional<CourseLocation> conflictLocation = courseLocationDao.findByBuildingAndRoomNumber(
                    newLocation.getBuilding(), newLocation.getRoomNumber());

            if (conflictLocation.isPresent() &&
                    !conflictLocation.get().getId().equals(locationToUpdate.getId())) {
                return Response.error("新的教室位置已存在: " +
                        newLocation.getBuilding() + "-" + newLocation.getRoomNumber());
            }

            // 3. 更新信息
            locationToUpdate.setBuilding(newLocation.getBuilding());
            locationToUpdate.setRoomNumber(newLocation.getRoomNumber());

            boolean ret = courseLocationDao.update(locationToUpdate);
            if (ret) {
                logger.info("教室位置更新成功: ID={}, {}-{} -> {}-{}",
                        locationToUpdate.getId(),
                        originLocation.getBuilding(), originLocation.getRoomNumber(),
                        newLocation.getBuilding(), newLocation.getRoomNumber());
                return Response.success(true);
            } else {
                return Response.error("更新教室位置失败");
            }
        } catch (Exception e) {
            logger.error("更新教室位置失败: {}-{} -> {}-{}, {}",
                    originLocation.getBuilding(), originLocation.getRoomNumber(),
                    newLocation.getBuilding(), newLocation.getRoomNumber(),
                    e.getMessage());
            return Response.error("更新失败: " + e.getMessage());
        }
    }
    /**
     * 删除教室信息。
     *
     * @param location 教室对象
     * @return Response 封装操作结果
     */
    @Override
    public Response<Boolean> deleteLocation(CourseLocation location) {
        try {
            logger.info("删除教室位置: {}-{}", location.getBuilding(), location.getRoomNumber());

            // 1. 根据楼栋和房间号查找教室位置
            Optional<CourseLocation> existingLocation = courseLocationDao.findByBuildingAndRoomNumber(
                    location.getBuilding(), location.getRoomNumber());

            if (existingLocation.isEmpty()) {
                return Response.error("教室位置不存在: " +
                        location.getBuilding() + "-" + location.getRoomNumber());
            }

            CourseLocation locationToDelete = existingLocation.get();

            // 2. 检查该教室是否有排课（这里需要根据您的业务逻辑实现）
            // if (hasScheduledCourses(locationToDelete.getId())) {
            //     return Response.error("该教室有排课安排，无法删除");
            // }

            // 3. 删除教室位置
            boolean ret = courseLocationDao.deleteById(locationToDelete.getId());
            if (ret) {
                logger.info("教室位置删除成功: ID={}, {}-{}",
                        locationToDelete.getId(),
                        location.getBuilding(), location.getRoomNumber());
                return Response.success(true);
            } else {
                return Response.error("删除教室位置失败");
            }
        } catch (Exception e) {
            logger.error("删除教室位置失败: {}-{}, {}",
                    location.getBuilding(), location.getRoomNumber(),
                    e.getMessage());
            return Response.error("删除失败: " + e.getMessage());
        }
    }
    /**
     * 根据教学楼查询教室列表。
     *
     * @param building 教学楼名称
     * @return Response 封装教室列表或错误信息
     */
    @Override
    public Response<List<CourseLocation>> findByBuilding(String building){
        try {
            logger.info("根据教学楼查询教室位置: building={}", building);
            List<CourseLocation> locations = courseLocationDao.findByBuilding(building);
            return Response.success(locations);
        } catch (Exception e) {
            logger.error("根据教学楼查询教室位置失败: building={}, {}", building, e.getMessage());
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 根据教室号查询教室列表。
     *
     * @param roomNumber 教室号
     * @return Response 封装教室列表或错误信息
     */
    @Override
    public Response<List<CourseLocation>> findByRoomNumber(String roomNumber) {
        try {
            logger.info("根据教室号查询教室位置: roomNumber={}", roomNumber);
            List<CourseLocation> location = courseLocationDao.findByRoomNumber(roomNumber);
            return Response.success(location);
        } catch (Exception e) {
            logger.error("根据教室号查询教室位置失败: roomNumber={}, {}", roomNumber, e.getMessage());
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 根据教学楼和教室号查询教室位置。
     *
     * @param building 教学楼名称
     * @param roomNumber 教室号
     * @return Response 封装教室对象或错误信息
     */
    @Override
    public Response<CourseLocation> findByBuildingAndRoomNumber(String building, String roomNumber) {
        try {
            logger.info("根据教学楼和教室号查询: building={}, roomNumber={}", building, roomNumber);
            Optional<CourseLocation> location = courseLocationDao.findByBuildingAndRoomNumber(building, roomNumber);
            return location.map(Response::success).orElseGet(() -> Response.error("教室位置不存在: " + building + "-" + roomNumber));
        } catch (Exception e) {
            logger.error("根据教学楼和教室号查询失败: building={}, roomNumber={}, {}",
                    building, roomNumber, e.getMessage());
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 查询教室总数量。
     *
     * @return Response 封装教室总数或错误信息
     */
    @Override
    public Response<Long> getLocationCount() {
        try {
            logger.info("统计教室位置数量");
            long count = courseLocationDao.count();
            return Response.success(count);
        } catch (Exception e) {
            logger.error("统计教室位置数量失败: {}", e.getMessage());
            return Response.error("统计失败: " + e.getMessage());
        }
    }
    /**
     * 根据学生 ID 查询已选课程。
     *
     * @param studentId 学生 ID
     * @return Response 封装课程列表或错误信息
     */
    @Override
    public Response<List<Course>> findSelectedCourseByStudentId(Long studentId){
        try {
            logger.info("根据学生ID查找已选课程中{}", studentId);
            List<Course> selectedCourses = courseDao.findSelectedCourseByStudentId(studentId);
            return Response.success(selectedCourses);
        } catch (Exception e) {
            logger.info("根据学生ID查找已选课程失败{}", studentId);
            return Response.error("查询失败: " + e.getMessage());
        }
    }
    /**
     * 校验课程对象的合法性。
     *
     * @param course 待验证课程对象
     * @throws RuntimeException 验证失败时抛出异常
     */
    // 私有辅助方法
    private void validateCourse(Course course) {
        if (course.getCourseCode() == null || course.getCourseCode().trim().isEmpty()) {
            throw new RuntimeException("课程代码不能为空");
        }
        if (course.getCourseName() == null || course.getCourseName().trim().isEmpty()) {
            throw new RuntimeException("课程名称不能为空");
        }
        if (course.getWeekStart() == null || course.getWeekEnd() == null) {
            throw new RuntimeException("课程的起止时间不能为空");
        }
        if (course.getClassPeriod() == null || course.getClassPeriod() <= 0) {
            throw new RuntimeException("课程的总课时数必须为正整数且非空");
        }
        if (course.getTeacherId() == null) {
            throw new RuntimeException("教师ID不能为空");
        }
        if (course.getCredit() == null || course.getCredit() <= 0) {
            throw new RuntimeException("学分必须大于0");
        }
        if (course.getMaxCapacity() == null || course.getMaxCapacity() <= 0) {
            throw new RuntimeException("最大容量必须大于0");
        }
        if (course.getCurrentEnrollment() != null &&
                course.getCurrentEnrollment() > course.getMaxCapacity()) {
            throw new RuntimeException("当前选课人数不能超过最大容量");
        }
        if (course.getSemester() == null) {
            throw new RuntimeException("课程的学期不能为空");
        }
    }

    /**
     * 准备课程响应数据，将课程及其排课信息映射为 Map。
     *
     * @param course 课程对象
     * @return Map 封装课程及排课信息
     */
    private Map<String, Object> prepareCourseResponse(Course course) {
        Map<String, Object> responseMap = new HashMap<>();

        // 设置基本属性
        responseMap.put("id", course.getId());
        responseMap.put("courseCode", course.getCourseCode());
        responseMap.put("courseName", course.getCourseName());
        responseMap.put("teacherId", course.getTeacherId());
        responseMap.put("credit", course.getCredit());
        responseMap.put("maxCapacity", course.getMaxCapacity());
        responseMap.put("weekStart", course.getWeekStart());
        responseMap.put("weekEnd", course.getWeekEnd());
        responseMap.put("classPeriod", course.getClassPeriod());
        responseMap.put("currentEnrollment", course.getCurrentEnrollment());
        responseMap.put("semester", course.getSemester());
        responseMap.put("description", course.getDescription());
        responseMap.put("status", course.getStatus());
        responseMap.put("isDeleted", course.getIsDeleted());

        // 处理嵌套的schedules
        if (course.getSchedules() != null && !course.getSchedules().isEmpty()) {
            List<Map<String, Object>> scheduleMaps = new ArrayList<>();
            for (CourseSchedule schedule : course.getSchedules()) {
                Map<String, Object> scheduleMap = new HashMap<>();
                scheduleMap.put("id", schedule.getId());
                scheduleMap.put("courseId", schedule.getCourseId());
                scheduleMap.put("dayOfWeek", schedule.getDayOfWeek());
                scheduleMap.put("startTime", schedule.getStartTime());
                scheduleMap.put("endTime", schedule.getEndTime());
                scheduleMap.put("location", schedule.getLocation());
                scheduleMaps.add(scheduleMap);
            }
            responseMap.put("schedules", scheduleMaps);
        }

        return responseMap;
    }
}
